package com.zjzaki.thingsboard.activity.bluetooth;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.zjzaki.thingsboard.common.GlobalDef;
import com.zjzaki.thingsboard.common.LoadingDialog;
import com.zjzaki.thingsboard.util.BluetoothUtil;


public class BluetoothBaseActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 接收文件路径
     */
    public static final String RECEIVE_FILE_PATH = "/sdcard/BluetoothRec/";
    /**
     * 字符类型
     */
    public static final int DATATYPE_STR = 0;
    /**
     * 16进制类型
     */
    public static final int DATATYPE_HEX = 1;
    /**
     * 应用程序环境的全局信息的接口
     */
    protected Context mContext = null;
    /**
     * 文本组件
     */
    protected TextView txt_msg_bluetooth;
    /**
     * 当前选择的发送数据类型
     */
    protected int mCurDataType = DATATYPE_STR;
    /**
     * 蓝牙适配器
     */
    protected BluetoothAdapter mBluetoothAdapter;
    /**
     * 连接加载弹窗
     */
    protected LoadingDialog loadingDialog = null;

    /**
     * 异步通信Handler
     */
    private Handler mBaseHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case GlobalDef.MSG_SHOW_TIP: {
                    if (txt_msg_bluetooth != null) {
                        String strTip = msg.obj.toString();
                        txt_msg_bluetooth.append(strTip + "\n");
                        int offset = txt_msg_bluetooth.getLineCount() * txt_msg_bluetooth.getLineHeight();
                        if (offset > txt_msg_bluetooth.getHeight()) {
                            txt_msg_bluetooth.scrollTo(0, offset - txt_msg_bluetooth.getHeight());
                        }
                    }
                    break;
                }
                case GlobalDef.MSG_CLEAN_TIP: {
                    if (txt_msg_bluetooth != null) {
                        txt_msg_bluetooth.setText("");
                        txt_msg_bluetooth.scrollTo(0, 0);
                    }
                    break;
                }
                case GlobalDef.MSG_SHOW_TOAST: {
                    String strTip = msg.obj.toString();
                    if (mContext != null) {
                        Toast.makeText(mContext, strTip, Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case GlobalDef.MSG_SHOW_LOAD_DIALOG: {
                    String strTip = msg.obj.toString();
                    if (loadingDialog != null) {
                        loadingDialog.show(strTip);
                    }
                    break;
                }
                case GlobalDef.MSG_CLOSE_LOAD_DIALOG: {
                    if (loadingDialog != null) {
                        loadingDialog.dismiss();
                    }
                    break;
                }
            }
        }
    };

    /**
     * 信息显示在文本组件中
     * @param strTip
     */
    public void showTip(String strTip) {
        Message msg = Message.obtain();
        msg.what = GlobalDef.MSG_SHOW_TIP;
        msg.obj = strTip;
        mBaseHandler.sendMessage(msg);
    }

    /**
     * 清空文本组件中的内容
     */
    public void cleanTip() {
        mBaseHandler.sendEmptyMessage(GlobalDef.MSG_CLEAN_TIP);
    }

    /**
     * 显示消息
     * @param strTip 消息内容
     */
    public void showToast(String strTip) {
        Message msg = Message.obtain();
        msg.what = GlobalDef.MSG_SHOW_TOAST;
        msg.obj = strTip;
        mBaseHandler.sendMessage(msg);
    }

    /**
     * 显示（或更新）加载对话框
     *
     * @param strTip 显示内容
     */
    public void showLoadingDialog(String strTip) {
        Message message = Message.obtain();
        message.what = GlobalDef.MSG_SHOW_LOAD_DIALOG;
        message.obj = strTip;
        mBaseHandler.sendMessage(message);
    }

    /**
     * 关闭加载对话框
     */
    public void dismissLoadingDialog() {
        mBaseHandler.sendEmptyMessage(GlobalDef.MSG_CLOSE_LOAD_DIALOG);
    }

    /**
     * 点击事件
     * @param v 页面视图
     */
    @Override
    public void onClick(View v) {

    }

    /**
     * 打开蓝牙
     */
    @SuppressLint("MissingPermission")
    public void openBluetooth() {

        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, GlobalDef.REQ_CODE_OPEN_BT);

        if (mBluetoothAdapter == null) {
            showToast("当前设备不支持蓝牙功能！");
            return;
        }

        if (mBluetoothAdapter.isEnabled()) {
            showToast("蓝牙已打开");
            return;
        }
    }

    /**
     * 关闭蓝牙
     */
    @SuppressLint("MissingPermission")
    public void closeBluetooth() {
        if (mBluetoothAdapter == null) {
            showTip("当前设备不支持蓝牙功能！");
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            showTip("当前蓝牙未打开");
            return;
        }

        mBluetoothAdapter.disable();
    }

    /**
     * 打开蓝牙可见性
     */
    public void openDiscovery() {
        if (mBluetoothAdapter == null) {
            showTip("当前设备不支持蓝牙功能！");
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            showTip("当前蓝牙未打开");
            return;
        }

        //启动修改蓝牙可见性的Intent
        //Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        //设置蓝牙可见性的时间，默认持续时间为120秒，每个请求的最长持续时间上限为300秒
        //intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
        //startActivity(intent);

        BluetoothUtil.setDiscoverableTimeout(mBluetoothAdapter, 0);
        showTip("当前设备蓝牙可见性永久开启");
    }

    /**
     * 关闭蓝牙可见性
     */
    public void closeDiscovery() {
        if (mBluetoothAdapter == null) {
            showTip("当前设备不支持蓝牙功能！");
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            showTip("当前蓝牙未打开");
            return;
        }

        BluetoothUtil.closeDiscoverableTimeout(mBluetoothAdapter);
        showTip("当前设备蓝牙可见性关闭");
    }


    /**
     * 得到百分比
     *
     * @param a
     * @param b
     * @return
     */
    public int getPercent(double a, double b) {
        if (b == 0) {
            return -1;
        }

        double result = a / b * 100;
        int iRet = (int) result;
        return iRet;
    }

    /*@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==GlobalDef.REQ_CODE_OPEN_BT){
            if(resultCode == Activity.RESULT_OK){
                showTip("蓝牙打开成功");
            }
            else{
                showTip("蓝牙打开失败");
            }
        }
    }*/
}
